<template>
    <div class="madp-customer-churn-set">
        <basic-container>
            <el-table
                :header-cell-style="{
                    background: 'rgb(255, 191, 191)',
                    color: 'rgb(44,44,44)'
                }"
                stripe
                :data="setData"
                v-loading="setLoading"
            >
                <el-table-column label="序号" align="center">
                    <template slot-scope="scope">{{ scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column prop="type" label="提醒类型" align="center"></el-table-column>
                <el-table-column prop="rule" label="设置规则" align="center" width="800">
                    <template slot-scope="scope">{{ scope.row.rule || '--' }}</template>
                </el-table-column>
                <el-table-column label="操作" align="center" v-if="permissions.cp_customer_churn_set_opt">
                    <template slot-scope="scope">
                        <el-switch v-if="scope.row.type == '被删除提醒'" v-model="scope.row.switch" @change="changeSwitch"></el-switch>
                        <div v-else>
                            <el-button v-if="isRule == false" type="text" @click="openDialog('新增规则')">设置</el-button>
                            <div v-else>
                                <el-button type="text" @click="openDialog('修改规则')">修改</el-button>
                                <el-button type="text" @click="deleteSet">删除</el-button>
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-dialog :title="tittle" :visible.sync="dialogRuleVisible" width="50%" :before-close="dialogRuleClose" :close-on-click-modal="false">
                <el-form v-if="dialogRuleVisible" ref="form" class="madp-form-style" :rules="rules" :model="dialogRuleForm" label-width="140px">
                    <el-form-item label="标签:">
                        <template>
                            <div class="madp-form-tag" v-for="(item, index) in tagList" :key="index">
                                <div class="madp-form-tag-group">
                                    <p>{{ item.groupName }}:</p>
                                </div>
                                <div class="madp-form-tag-item">
                                    <el-tag
                                        v-for="it in item.tagNameList"
                                        :key="it.id"
                                        :color="selectedTagId.includes(it.id) ? theme : '#ffffff'"
                                        :style="selectedTagId.includes(it.id) ? 'color: #ffffff' : 'color: #000000'"
                                        @click="onSelectTagChange(it)"
                                        >{{ it.name }}</el-tag
                                    >
                                </div>
                            </div>
                        </template>
                    </el-form-item>
                    <el-form-item label="触发时间/天:" prop="time">
                        <el-input
                            placeholder="设置未交流时长或流失客户时间，到达时间触发提醒"
                            style="width: 400px"
                            v-model.number="dialogRuleForm.time"
                            type="number"
                            @input="numberChange(arguments[1], 100)"
                            @change="numberChange(arguments[1], 100)"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="提醒频率:" prop="frequency">
                        <el-select v-model="dialogRuleForm.frequency">
                            <el-option v-for="item in frequencyOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="提醒次数:" prop="times">
                        <el-input maxlength="3" placeholder="到达次数后不在提醒" v-model.number="dialogRuleForm.times" type="text"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogRuleClose">取消</el-button>
                    <el-button type="primary" @click="dialogRuleconfirm">确定</el-button>
                </span>
            </el-dialog>
        </basic-container>
    </div>
</template>

<script>
import {
    getTagGroupList, // 获取客户标签组列表
    addRule, //新增规则
    delRule, //删除规则
    getStatus, //查询记录
    selectStatus, //开启、关闭
    updateRule, // 修改规则
    querystatus //查询状态
} from '@/api/customer-churn/customer-churn-set';
import { mapGetters } from 'vuex';
export default {
    name: 'madp-customer-churn-set',
    data() {
        return {
            // 初始数据
            initData: null,
            // 是否已有规则
            isRule: false,
            // 标题
            tittle: '',
            // 弹窗规则表单
            dialogRuleForm: {
                time: null,
                tags: this.selectedTagId,
                frequency: null,
                times: null
            },
            // 弹窗标题
            dialogTittle: '',
            // 弹窗开关
            dialogRuleVisible: false,
            // loading开关
            setLoading: false,
            // 表格数据
            setData: [
                {
                    type: '被删除提醒',
                    rule: '当企业微信被客户删除时，被删除的企业成员将收到一条消息提醒',
                    switch: 0
                },
                {
                    type: '未交流提醒',
                    rule: ''
                }
            ],
            // 标签数据
            tagList: [],
            // 已选标签
            selectedTag: [],
            //标签id list
            selectedTagId: [],
            // 标签id
            selectId: Number,
            // 提醒频率下拉框
            frequencyOptions: [
                {
                    label: '每小时',
                    value: 1
                },
                {
                    label: '每6小时',
                    value: 2
                },
                {
                    label: '每天',
                    value: 3
                },
                {
                    label: '每周',
                    value: 4
                },
                {
                    label: '每两周',
                    value: 5
                },
                {
                    label: '每月',
                    value: 6
                }
            ],
            // 表单校验规则
            rules: {
                time: [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入触发时间'));
                            } else if (isNaN(value) || value <= 0 || value > 100) {
                                callback(new Error('请输入1-100的整数'));
                            } else {
                                callback();
                            }
                        }
                    }
                ],
                frequency: [
                    {
                        required: true,
                        message: '请选择提醒频率',
                        trigger: 'change'
                    }
                ],
                times: [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入提醒次数'));
                            } else if (isNaN(value) || value <= 0 || value > 200) {
                                callback(new Error('请输入1-200的整数'));
                            } else {
                                callback();
                            }
                        }
                    }
                ]
            }
        };
    },
    computed: {
        ...mapGetters(['theme', 'permissions'])
    },
    mounted() {
        this.getAllTags();
        querystatus().then((res) => {
            if (res.data && res.data.code == 0) {
                this.setData[0].switch = Boolean(res.data.data.status);
            }
        });
        this.getRuleStatus();
    },
    methods: {
        // 获取规则状态
        getRuleStatus() {
            getStatus().then((res) => {
                if (res.data && res.data.code == 0) {
                    this.isRule = res.data.data.tagIds !== '';
                    this.selectId = res.data.data.id;
                    if (this.isRule) {
                        this.origTagId = res.data.data.tagIds;
                        this.selectedTagId = res.data.data.tagIds;
                        this.initData = res.data.data;
                        this.initData.frequency = Number(this.initData.frequency);
                    }
                }
            });
        },
        // 更改状态
        changeSwitch() {
            let status = this.setData[0].switch ? 1 : 0;
            selectStatus(status).then((res) => {
                if (res.data.code === 0) {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                }
            });
        },
        // 获取标签
        getAllTags() {
            getTagGroupList().then((res) => {
                if (res.data.code === 0) {
                    this.tagList = res.data.data;
                }
            });
        },
        // 更改tags
        onSelectTagChange(records) {
            const index = this.selectedTagId.findIndex((item) => item === records.id);
            if (index > -1) {
                this.selectedTagId.splice(index, 1);
                this.selectedTag.splice(index, 1);
            } else {
                this.selectedTagId.push(records.id);
                this.selectedTag.push(JSON.parse(JSON.stringify(records)));
            }
        },
        // 打开弹窗
        openDialog(tittle) {
            this.tittle = tittle;
            let tags = JSON.parse(JSON.stringify(this.origTagId || []));
            if (tittle == '修改规则') {
                this.selectedTagId = tags;
                this.dialogRuleForm = JSON.parse(JSON.stringify(this.initData));
            } else {
                this.dialogRuleForm = {
                    time: null,
                    tags: tags,
                    frequency: null,
                    times: null
                };
            }
            this.dialogRuleVisible = true;
        },
        // 关闭弹窗
        dialogRuleClose() {
            this.dialogRuleForm.time = '';
            this.selectedTagId = [];
            this.dialogRuleVisible = false;
        },
        // 点击确定
        dialogRuleconfirm() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let { frequency, time, times } = this.dialogRuleForm;
                    let data = {
                        tagIds: this.selectedTagId,
                        time,
                        frequency,
                        times
                    };
                    if (!this.isRule) {
                        addRule(data).then((res) => {
                            if (res.data && res.data.code == 0) {
                                this.getRuleStatus();

                                this.$message({
                                    type: 'success',
                                    message: '添加成功!'
                                });
                                this.dialogRuleVisible = false;
                            }
                        });
                    } else {
                        data.id = this.selectId;
                        updateRule(data).then((res) => {
                            if (res.data && res.data.code == 0) {
                                this.getRuleStatus();
                                this.$message({
                                    type: 'success',
                                    message: '修改成功!'
                                });
                                this.dialogRuleVisible = false;
                            }
                        });
                    }
                }
            });
        },
        // 删除规则
        deleteSet() {
            this.$confirm('您设置的未交流提醒规则即将删除, 是否继续?', '', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    delRule(this.selectId).then((res) => {
                        if (res.data && res.data.code == 0) {
                            this.getRuleStatus();
                            this.dialogRuleForm.time = '';
                            this.selectedTagId = [];
                            this.origTagId = [];
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }
                    });
                })
                .catch(() => {});
        },
        // 更改数字
        numberChange(val, maxNum) {
            this.dialogRuleForm.time = Number(this.dialogRuleForm.time);
            this.$nextTick(() => {
                let num = Math.min(this.dialogRuleForm.time, maxNum);
                if (num <= 0) {
                    this.dialogRuleForm.time = 1;
                } else {
                    this.dialogRuleForm.time = num;
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.madp-form-tag {
    display: flex;
    &-group {
        margin-right: 10px;
        p {
            width: max-content;
            min-width: 85px;
        }
    }
    &-item {
        .el-tag {
            margin: 0 5px 5px 0;
            cursor: pointer;
        }
    }
}
/deep/ .el-dialog {
    min-width: 800px !important;
}
</style>
